var toPage;
$(function () {
    loadBankInfo();
    // getBankStuff();
    bankInfoValidation();
});

function bankInfoValidation() {
    $('#bankInfoForm').bootstrapValidator({
        feedbackIcons: {
            valid: 'fa fa-check',

            validating: 'fa fa-sync-alt'
        },
        fields: {
            name: {
                validators: {
                    notEmpty: {},
                    stringLength: {
                        min: 1,
                        max: 16,
                    },
                    regexp: {
                        regexp: /^[\u4E00-\u9FA5a-zA-Z0-9_-]+$/,
                        message: '银行名称只能由汉字、字母、数字、横线和下划线组成'
                    }
                }
            },
            province: {
                validators: {
                    notEmpty: {
                        message: '请选择省份'
                    },
                    callback: {
                        message: '请选择省份',
                        callback: function (value, validator) {
                            if (!getSelectValue($('#province'))) {
                                return false;
                            } else {
                                return true;
                            }
                        }
                    }
                }
            }, city: {
                validators: {
                    notEmpty: {
                        message: '请选择市'
                    },
                    callback: {
                        message: '请选择市',
                        callback: function (value, validator) {
                            if (!getSelectValue($('#city'))) {
                                return false;
                            } else {
                                return true;
                            }
                        }
                    }
                }
            }, address: {
                validators: {
                    notEmpty: {
                        message: '请输入详细地址'
                    },
                }
            },
        }
    }).on('success.form.bv', function (e) {
        //防止表单提交
        e.preventDefault();
        //获取表单实例
        var $form = $(e.target);
        //获取BootstrapValidator实例
        jQuery.support.cors = true;
        var bv = $form.data('bootstrapValidator');
        var formData = new FormData($("#bankInfoForm")[0]);
        compressPicture($('#add_file_hide').prop('files')[0], 100, 100, 0.75, function(blob){
            if(!isNull(blob)){
            formData.append("minLogo",blob);
            }
        getJson4Multipart('/sys/org/save', formData, 'POST', function (data) {
            $('#bankInfoModal').modal('hide');
            if (data.code == 200) {
                myAlert("提示", "保存成功");
                loadBankInfo();
            } else {
                myAlert("提示", "保存失败");
            }
        });
        })
    }).on('error.form.bv', function (e) { //点击提交验证失败之后
        $('[type="submit"]').removeAttr("disabled");
    });
}

$("#page").paging({
    pageNo: 1,
    totalPage: 0,
    totalSize: 0,
    callback: function (num) {
    }
});

$('#bankInfoModal').on('hidden.bs.modal', function () {
    let form = $("#bankInfoForm");
    form.data('bootstrapValidator').destroy();
    form.data('bootstrapValidator', null);
    bankInfoValidation();
    form[0].reset();//清空表单
});

/*加载银行信息*/
function loadBankInfo() {
    getJson('/bank/info', null, 'GET', function (data) {
        if (data['code'] == 200) {
            let bank = data['payload']['bank'];
            $('#bId').val(bank['id']);
            $('#bName').text(bank['name']);
            $('#bAddress').text(bank['province'] + bank['city'] + bank['address']);
            $('#bLogo').attr('src', fileUrl + bank['logo']);
            buildEnterpriseBanner($('#creditCompany_List'), data['payload']['data']);
            loadBankStuff(bank['id']);
            $('#btn_bank_info_edit').removeAttr('disabled');
            $('#btn_bankStuff').removeAttr('disabled');
        } else {
            myAlert('警告', data['message']);
        }
    })
}

// 构建已授信企业
function buildEnterpriseBanner(parent, data) {
    $(parent).empty();
    for (let item of data) {
        let box = createElement('div', parent);
        $(box).addClass('col-3');
        let innerBox = createElement('div', box);
        $(innerBox).addClass('company-list').addClass('d-flex').addClass('align-items-center');
        let logo = createElement('img', innerBox);
        if(!isNull(item['logo'])){
        $(logo).attr('src', fileUrl + item['logo']);
        $(logo).attr('alt', '企业Logo');
        }
        let descBox = createElement('div', innerBox);
        $(descBox).addClass('ml-3');
        let name = createElement('div', descBox);
        $(name).addClass('mb-2');
        $(name).text(item['name']);
        let deviceCount = createElement('div', descBox);
        $(deviceCount).addClass('font-p14').addClass('text-secondary');
        $(deviceCount).text(item['deviceCount'] + '台');
    }
}

/*加载银行职员信息列表*/
function loadBankStuff(_pageIndex) {
    $('#bankInfoModal').modal('hide');
    showLoading(LOADING);
    let searchValue = $('#searchValue').val();
    let pageIndex = parseInt(_pageIndex ? _pageIndex : '1');
    toPage=  pageIndex;
    getJson('/sys/user/list', {
        searchValue: searchValue,
        pageIndex: pageIndex,
        pageSize: 10
    }, 'GET', function (data) {
        hideLoading();
        if (data['code'] == 200) {
            let payload = data['payload'];
            $("#page").paging({
                pageNo: pageIndex,
                totalPage: payload['pages'],
                totalSize: payload['total'],
                callback: function (num) {
                    loadBankStuff(num);
                }
            });
            let order = 1 + 10 * (pageIndex - 1);
            for (let item of payload['data']) {
                item['order'] = order++;
                if (!item['expire']) {
                    item['expire'] = '永久';
                } else {
                    item['expire'] = getDate(item['expire']).datetime();
                }
            }
            buildTable($('#stuffList'), title, label, payload['data'], function (td, label, item) {
                switch (label) {
                    case 'roleName':
                        if (item['roleSet'] && item['roleSet'].length > 0) {
                            $(td).text(item['roleSet'][0]['roleName'])
                        }
                        break;
                    case 'areaDisplay':
                        let areaSet = [];
                        if (item['areaSet']) {
                            for (let area of item['areaSet']) {
                                areaSet.push(area['name']);
                            }
                            $(td).text(areaSet.join(","));
                        }
                        break;
                    case 'status':
                        $(td).empty();
                        let span = createElement('span', td);
                        if (item['status'] == 1) {
                            $(span).text('启用');
                            $(span).addClass('text-success');
                        } else {
                            $(span).text('禁用');
                            $(span).addClass('text-danger');
                        }
                        break;
                    case 'desc':
                        $(td).empty();
                        $(td).text(item[label]);
                        break;
                    case 'opera':
                      if(bankInnerOpera){
                          let edit = createElement('a', td);
                          $(edit).addClass('font-p24');
                          $(edit).attr('href', '##');
                          $(edit).click(function () {
                              editUser(item['id']);
                          });
                          let editIcon = createElement('i', edit);
                          $(editIcon).addClass('iconfont');
                          $(editIcon).addClass('icon-bianji-');
                          let del = createElement('a', td);
                          $(del).addClass('font-p24');
                          $(del).addClass('delete-option-btn');
                          $(del).addClass('ml-2');
                          $(del).attr('href', '##');
                          $(del).click(function () {
                              delUser(item['id']);
                          });
                          let delIcon = createElement('i', del);
                          $(delIcon).addClass('iconfont');
                          $(delIcon).addClass('icon-shanchuicon');
                      }
                        break;
                }
            })
        }
    })
}

// 获取角色列表
function getRoleList(user) {
    let current = null;
    if (user['roleSet'].length > 0) {
        current = user['roleSet'][0]['id'];
    }
    getJson('/sys/role/list', null, 'GET', function (data) {
        buildSelect($('#role'), data['payload']['data'], 'roleName', 'id', current, function (option, item) {
            $(option).attr('expire', item['expire']);
        });
    })
}

$('#role').change(function () {
    let expire = $(this).find('option:selected').attr('expire');
    $('#expire').val(expire != 0 ? getDate(new Date(expire * 24 * 60 * 60 * 1000 + new Date().getTime()).getTime()).datetime() : '');
});

/*修改银行信息*/
function editBankInfo() {
    let bankId = $('#bId').val();
    if (!bankId) {
        return;
    }
    getJson('/sys/org/info', {id: bankId}, 'GET', function (data) {
        let bank = data['payload']['data'];
        getProvince($('#province'), bank['province'], $('#city'), bank['city']);
        $('#id').val(bank['id']);
        $('#name').val(bank['name']);
        $('#address').text(bank['address']);
        $('#img_load_area').attr('src', fileUrl + bank['logo']);
        $('#bankInfoModal').modal();
    });
}

/*修改用户信息*/
function editUser(id) {
    // 先清空
    resetForm($('#userInfoForm'));

    // 再填数据
    getJson('/sys/user/info', {id: id}, 'GET', function (data) {
        let user = data['payload']['data'];
        $('#id').val(user['id']);
        $('#username').val(user['username']);
        $('#displayName').val(user['displayName']);
        $('#status').val(user['status']);
        laydate.render({
            elem: '#expire',
            type: 'datetime'
        });
        if(user['expire']){
            $('#expire').val(getDate(user['expire']).datetime());
        }
        $('#desc').val(user['desc']);
        getRoleList(user);
        let areaData = [];
        if (user['organization']) {
            areaData = user['organization']['areaSet'];
        }
        buildAreaList($('#listGroup1'), areaData, user['area'].split(','));
        let areaSet = [];
        if (user['areaSet']) {
            for (let item of user['areaSet']) {
                areaSet.push(item['name']);
            }
        }
        $('#areaDisplayName').val(areaSet.join(','));
        $('#area').val(user['area']);
    });
    $('#userInfoModal').modal();
    //注意：选择角色后，自动根据角色的有效期生成用户有效期
}

// 保存用户信息
function saveUser() {
    let data = {};
    data['id'] = $('#id').val();
    data['username'] = $('#username').val();
    data['displayName'] = $('#displayName').val();
    data['role'] = getSelectValue($('#role'));
    data['enterprise'] = getSelectValue($('#organization'));
    data['area'] = $('#area').val();
    if (!data['area']) {
        myAlert('提示', '权限区域不能为空');
        return;
    }
    data['status'] = $('#status').val();
    data['expire'] = $('#expire').val();
    data['desc'] = $('#desc').val();

    getJson('/sys/user/save', data, 'POST', function (data) {
        $('#userInfoModal').modal('hide');
        switch (data['code']){
            case 200:
                myAlert('提示', data['message'], function () {
                    loadBankStuff($('#bId').val());
                });
                break;
            case 302:
                myAlert('提示', data['message'], function () {
                    top.location.href = '../index.html';
                });
                break;
            default:
                myAlert('提示', data['message']);
        }

    })
}

// 删除用户
function delUser(id) {
    myConfirm('提示', '是否删除用户', function (result) {
        if (result) {
            getJson('/sys/user/delete', {
                id: id
            }, 'GET', function (data) {
                loadBankStuff($('#bId').val());
                if (data['code'] == 200) {
                    myAlert('提示', '删除成功');
                } else {
                    myAlert('提示', '删除失败');
                }
            })
        }
    })
}

//点击加载企业列表
$('#areaDisplayName').click(function () {
    $('#listGroup1').slideDown(0);
})

//确认选择勾选企业
function confirmSelection() {
    $('#area').val('');
    $('#areaDisplayName').val('');
    var value = [];
    var name = [];
    $.each($('input:checkbox[name=companyList]:checked'), function () {
        value.push($(this).val());
        name.push($(this).attr('eName'))
    });
    $('#area').val(value.join(','));
    $('#areaDisplayName').val(name.join(','));
    $('#listGroup1').slideUp(0);
}

//全选
function selectAll() {
    $('input:checkbox[name=companyList]').prop("checked", true);
    confirmSelection();
}

//取消选择企业
function cancelSelection() {
    $('#listGroup1').slideUp(0);
}

/*选择的图片加载到预览区*/
$('#add_file_hide').change(function (e) {
    if(this.files[0].size /1024 /1024 >10){
        myAlert("提示","选择的图片不能超过10M");
        return;
    }
    var _URL = window.URL || window.webkitURL;
    var file, img;
    if ((file = this.files[0])) {
        img = new Image();0
        img.onload = function () {
            $('#img_load_area').attr('src', this.src);
        };
        img.src = _URL.createObjectURL(file);
    }
})



